import {
  Form,
  Button,
  Col,
  Row,
  Input,
  Select,
  DatePicker,
  Card,
  Space,
  message,
  InputNumber,
} from "antd";
import React, { Component } from "react";
import { Productonsalelist, Inquiryadd } from "../../../services/auth";
import { getToken } from "../../../utils/auth";
import { PlusOutlined, MinusCircleOutlined } from "@ant-design/icons";

// form中的属性
const { Option } = Select;
const { RangePicker } = DatePicker;

export default class CreateInquiry extends Component {
  constructor(props) {
    super(props);
    const { handleCreateClick } = this.props;
    this.handleCreateClick = handleCreateClick;
    this.state = {
      // 这个是商品数据
      dataSource: [],
      // 这个是可用于生成询价单的商品列表
      productList: [],
    };
    // editableTable的列
    this.columns = [
      {
        title: "产品编号",
        dataIndex: "goods_id",
      },
      {
        title: "产品名称",
        dataIndex: "goods_name",
      },
      {
        title: "订货数量",
        dataIndex: "quantity",
      },
      {
        title: "产品定价",
        dataIndex: "price",
      },
      {
        title: "折扣（可编辑）",
        dataIndex: "discount",
        width: "15%",
        editable: true,
      },
      {
        title: "产品价格",
        dataIndex: "current_price",
      },
    ];
    this.user = JSON.parse(getToken());
  }
  formRef = React.createRef();
  componentDidMount() {
    Productonsalelist().then(
      (response) => {
        //拿到我们想要渲染的数据(res)
        this.setState({
          productList: response.data,
        });
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }
  // 点击提交后触发的事件
  onFinish = (values) => {
    console.log(values);
    Inquiryadd({
      goods: values.goods,
      ship_to_address: values.ship_to_address,
      valid_from: values.valid[0].format("YYYY-MM-DD"),
      valid_to: values.valid[1].format("YYYY-MM-DD"),
      req_deliv_date: values.req_deliv_date.format("YYYY-MM-DD"),
      agent_id: this.user.id,
      company_id: this.user.company_id,
    }).then(
      (response) => {
        if (response.data.result === "success") {
          message.success("询价单" + response.data.inquiry_id + "已创建成功");
          this.formRef.current.resetFields();
          this.handleCreateClick();
        } else {
          message.info("提交失败，请重试");
        }
      },
      (error) => {
        console.log("数据获取失败", error);
      }
    );
  };
  onReset = () => {
    this.formRef.current.resetFields();
  };
  // 用于editableTable的函数
  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      name: `Edward King ${count}`,
      age: "32",
      address: `London, Park Lane no. ${count}`,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
    });
  };
  handleSave = (row) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
      current_price: (row.discount * row.price) / 100,
    });
    this.setState({
      dataSource: newData,
    });
  };

  render() {
    return (
      <Form
        layout="vertical"
        hideRequiredMark
        onFinish={this.onFinish}
        ref={this.formRef}
      >
        <Row gutter={24}>
          <Col span={6}>
            <Form.Item
              name="valid"
              label="生效期限"
              rules={[{ required: true, message: "请填写生效期限" }]}
            >
              <RangePicker />
            </Form.Item>
          </Col>
          <Col span={3}>
            <Form.Item
              name="req_deliv_date"
              label="送达日期"
              rules={[{ required: true }]}
            >
              <DatePicker />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              name="ship_to_address"
              label="送货地点"
              rules={[{ required: true, message: "请输入送货地点" }]}
            >
              <Input />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24} />
        {/* editableTable */}
        <Form.List name="goods">
          {(fields, { add, remove }) => (
            <div>
              {fields.map(({ key, name, fieldKey, ...restField }) => (
                <Space
                  key={key}
                  style={{ display: "flex", width: "100%" }}
                  direction="vertical"
                >
                  <Card>
                    <Row gutter={24}>
                      <Col span={8}>
                        <Form.Item
                          {...restField}
                          name={[name, "goods_id"]}
                          label="商品"
                          fieldKey={[fieldKey, "goods_id"]}
                          rules={[{ required: true, message: "请选择商品" }]}
                        >
                          <Select onSelect={this.onSelect}>
                            {this.state.productList.map((product, index) => (
                              <Option value={product.id}>
                                {product.id + " " + product.name}
                              </Option>
                            ))}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={8}>
                        <Form.Item
                          {...restField}
                          name={[name, "quantity"]}
                          label="数量"
                          fieldKey={[fieldKey, "quantity"]}
                          rules={[
                            { required: true, message: "请输入商品数量" },
                          ]}
                        >
                          <Input />
                        </Form.Item>
                      </Col>
                      <Col span={8}>
                        <Form.Item
                          {...restField}
                          name={[name, "trans_rate"]}
                          label="转化率"
                          fieldKey={[fieldKey, "trans_rate"]}
                          rules={[{ required: true, message: "请输入转化率" }]}
                        >
                          <InputNumber
                            min={0}
                            max={100}
                            formatter={(value) => `${value}%`}
                            parser={(value) => value.replace("%", "")}
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Card>
                  <MinusCircleOutlined onClick={() => remove(name)} />
                </Space>
              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                >
                  添加商品
                </Button>
              </Form.Item>
            </div>
          )}
        </Form.List>

        <Form.Item>
          <div
            style={{
              textAlign: "right",
            }}
          >
            <Button onClick={this.onClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button htmlType="reset" style={{ marginRight: 8 }}>
              重置
            </Button>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </div>
        </Form.Item>
      </Form>
    );
  }
}
